import json
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.core.paginator import Paginator
from django.contrib.auth.hashers import make_password, check_password
from app.models import TravelInfo, User
from django.db.models import F, Count


def login(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")

        if not username or not password:
            return JsonResponse({"status": "err", "msg": "用户名或密码不为空"})

        user = User.objects.filter(username=username).first()
        if user:
            # 密码校验
            if check_password(password, user.password):
                if user.avatar:
                    avatar_url = user.avatar.url
                else:
                    avatar_url = "/static/img/default.png"

                # 登录成功
                request.session["id"] = user.id
                request.session["username"] = user.username
                request.session["avatar"] = avatar_url
                request.session["textarea"] = user.textarea

                return JsonResponse({"status": "ok", "msg": "登录成功"})
            else:
                return JsonResponse({"status": "err", "msg": "用户密码错误"})
        else:
            return JsonResponse({"status": "err", "msg": "该用户不存在，请创建账号"})

    return render(request, "login.html")


def register(request):
    if request.method == "POST":
        username = request.POST.get("username")
        password = request.POST.get("password")
        confirm_password = request.POST.get("confirmPassword")

        if not username or not password or not confirm_password:
            return JsonResponse({"status": "err", "msg": "用户名或密码不允许为空"})
        elif password != confirm_password:
            return JsonResponse({"status": "err", "msg": "两次密码不一致"})
        elif User.objects.filter(username=username).exists():
            return JsonResponse({"status": "err", "msg": "该用户名已存在"})
        else:
            # 密码加密
            password = make_password(password)
            User.objects.create(username=username, password=password)
            return JsonResponse({"status": "ok", "msg": "注册成功"})

    return render(request, "register.html")


def logout(request):
    request.session.clear()
    return redirect("/app/login")


def index(request):
    count_5a = TravelInfo.objects.filter(level="AAAAA").count()
    obj = TravelInfo.objects.order_by("-comment_total").first()

    # print(obj.title)

    obj1 = (
        TravelInfo.objects.values("province")
        .annotate(total=Count("id"))
        .order_by("-total")
        .first()
    )

    province = obj1.get("province") + " (" + str(obj1.get("total")) + "个)"

    result = (
        TravelInfo.objects.annotate(name=F("province"))
        .values("name")
        .annotate(value=Count("id"))
        .order_by("-value")
    )

    provinces = [item["name"] for item in result]
    values = [item["value"] for item in result]

    top10 = TravelInfo.objects.all().order_by("-score", "-interestNum")[:10]

    return render(
        request,
        "index.html",
        {
            "count_5a": count_5a,
            "title": obj.title,
            "province": province,
            "provinces": json.dumps(provinces, ensure_ascii=False),
            "values": json.dumps(values, ensure_ascii=False),
            "top10": top10,
        },
    )


def changeUserInfo(request):
    username = request.session.get("username")
    user = User.objects.get(username=username)

    if request.method == "POST":
        sex = request.POST.get("sex")
        address = request.POST.get("address")
        textarea = request.POST.get("textarea") or "这个人很懒，什么有没留下。"

        user.sex = sex
        user.address = address
        user.textarea = textarea
        avatar = request.FILES.get("avatar")
        if avatar:
            id = request.session.get("id")
            # 用 id 作为文件名，防不同用户同文件名覆盖
            ext = avatar.name.split(".")[-1]
            filename = f"{id}.{ext}"
            user.avatar.save(filename, avatar)
        user.save()

        # 更新用户session
        request.session["avatar"] = user.avatar.url
        request.session["textarea"] = textarea
        return redirect("/app/changeUserInfo")

    return render(request, "changeUserInfo.html", {"user": user})


def changePassword(request):
    if request.method == "POST":
        oldPassword = request.POST.get("oldPassword")
        newPassword = request.POST.get("newPassword")
        newPasswordConfirm = request.POST.get("newPasswordConfirm")

        if not oldPassword or not newPassword or not newPasswordConfirm:
            return JsonResponse({"status": "err", "msg": "参数不能为空"})

        username = request.session.get("username")
        user = User.objects.get(username=username)

        if newPassword != newPasswordConfirm:
            return JsonResponse({"status": "err", "msg": "两次密码输入不一致"})

        if check_password(oldPassword, user.password):
            password = make_password(newPassword)
            user.password = password
            user.save()

            return JsonResponse({"status": "ok", "msg": "密码修改成功"})
        else:
            return JsonResponse({"status": "err", "msg": "原始密码不正确"})

    return render(request, "changePassword.html")


def tableData(request):
    page = request.GET.get("page", 1)  # 当前页
    page_size = 10  # 每页 10 条

    qs = TravelInfo.objects.order_by("id")  # 排序
    paginator = Paginator(qs, page_size)  # 创建分页器
    page_obj = paginator.get_page(page)  # 获取当前页数据

    return render(request, "tableData.html", {"page_obj": page_obj, "page": page})


def detail(request):
    id = request.GET.get("id")
    page = request.GET.get("page", 1)
    travelInfo = TravelInfo.objects.get(id=id)
    img_list = json.loads(travelInfo.img_list)
    commentList = json.loads(travelInfo.commentList)
    print(commentList)
    return render(
        request,
        "detail.html",
        {
            "travelInfo": travelInfo,
            "img_list": img_list,
            "page": page,
            "commentList": commentList,
        },
    )
